document.addEventListener('DOMContentLoaded', function() {
    // 初始化购物车
    initCart();
    
    // 添加到购物车按钮事件
    const addToCartButtons = document.querySelectorAll('.add-to-cart');
    addToCartButtons.forEach(button => {
        button.addEventListener('click', function() {
            const productId = this.getAttribute('data-product-id');
            const productName = this.getAttribute('data-product-name');
            const productPrice = parseFloat(this.getAttribute('data-product-price'));
            const productImage = this.getAttribute('data-product-image');
            
            addToCart(productId, productName, productPrice, productImage);
        });
    });
    
    // 更新购物车数量
    updateCartCount();
    
    // 购物车页面特定逻辑
    if (window.location.pathname.includes('cart.html')) {
        renderCartItems();
        initCartItemEvents();
    }
    
    // 结账页面特定逻辑
    if (window.location.pathname.includes('checkout.html')) {
        renderCheckoutItems();
        calculateCheckoutTotals();
    }
});

// 初始化购物车
function initCart() {
    if (!localStorage.getItem('cart')) {
        localStorage.setItem('cart', JSON.stringify([]));
    }
}

// 添加商品到购物车
function addToCart(productId, name, price, image, quantity = 1) {
    const cart = JSON.parse(localStorage.getItem('cart')) || [];
    
    // 检查商品是否已在购物车中
    const existingItemIndex = cart.findIndex(item => item.id === productId);
    
    if (existingItemIndex !== -1) {
        // 商品已在购物车中，增加数量
        cart[existingItemIndex].quantity += quantity;
    } else {
        // 商品不在购物车中，添加新商品
        cart.push({
            id: productId,
            name: name,
            price: price,
            image: image,
            quantity: quantity
        });
    }
    
    // 保存购物车
    localStorage.setItem('cart', JSON.stringify(cart));
    
    // 更新购物车数量
    updateCartCount();
    
    // 显示成功通知
    showNotification(`${name} 已添加到购物车`, 'success');
}

// 更新购物车数量显示
function updateCartCount() {
    const cart = JSON.parse(localStorage.getItem('cart')) || [];
    const totalQuantity = cart.reduce((total, item) => total + item.quantity, 0);
    const cartCountElement = document.getElementById('cart-count');
    
    if (cartCountElement) {
        cartCountElement.textContent = totalQuantity;
    }
}

// 渲染购物车商品
function renderCartItems() {
    const cart = JSON.parse(localStorage.getItem('cart')) || [];
    const cartItemsContainer = document.getElementById('cart-items');
    
    if (!cartItemsContainer) return;
    
    // 清空容器
    cartItemsContainer.innerHTML = '';
    
    if (cart.length === 0) {
        // 购物车为空
        cartItemsContainer.innerHTML = `
            <div class="flex flex-col items-center justify-center py-16">
                <i class="fa fa-shopping-cart text-6xl text-light-3 mb-4"></i>
                <h3 class="text-xl font-medium mb-2">购物车是空的</h3>
                <p class="text-dark-2 mb-6">快去添加商品吧！</p>
                <a href="index.html" class="btn-primary px-6 py-2">开始购物</a>
            </div>
        `;
        document.getElementById('cart-summary').classList.add('hidden');
        return;
    }
    
    // 显示购物车商品
    let subtotal = 0;
    
    cart.forEach(item => {
        const itemTotal = item.price * item.quantity;
        subtotal += itemTotal;
        
        const cartItem = document.createElement('div');
        cartItem.className = 'cart-item flex items-center py-4 border-b border-light-2';
        cartItem.innerHTML = `
            <div class="cart-item-image w-24 h-24 rounded-lg overflow-hidden">
                <img src="${item.image}" alt="${item.name}" class="w-full h-full object-cover">
            </div>
            <div class="ml-4 flex-1">
                <h3 class="font-medium">${item.name}</h3>
                <div class="flex items-center mt-4">
                    <div class="flex items-center border rounded-lg">
                        <button class="cart-decrease px-3 py-1 text-dark-2 hover:text-primary transition-colors" data-product-id="${item.id}">
                            <i class="fa fa-minus"></i>
                        </button>
                        <input type="number" value="${item.quantity}" min="1" class="cart-quantity w-12 text-center border-x border-light-2 py-1 focus:outline-none" data-product-id="${item.id}">
                        <button class="cart-increase px-3 py-1 text-dark-2 hover:text-primary transition-colors" data-product-id="${item.id}">
                            <i class="fa fa-plus"></i>
                        </button>
                    </div>
                    <div class="ml-auto text-right">
                        <p class="text-dark-2 line-through">¥${(item.price * 1.2).toFixed(2)}</p>
                        <p class="font-bold text-lg">¥${itemTotal.toFixed(2)}</p>
                    </div>
                    <button class="cart-remove ml-4 text-dark-2 hover:text-danger transition-colors" data-product-id="${item.id}">
                        <i class="fa fa-trash-o"></i>
                    </button>
                </div>
            </div>
        `;
        
        cartItemsContainer.appendChild(cartItem);
    });
    
    // 更新小计和总计
    document.getElementById('subtotal-amount').textContent = `¥${subtotal.toFixed(2)}`;
    document.getElementById('total-amount').textContent = `¥${subtotal.toFixed(2)}`;
}

// 初始化购物车商品事件
function initCartItemEvents() {
    // 减少数量按钮
    document.querySelectorAll('.cart-decrease').forEach(button => {
        button.addEventListener('click', function() {
            const productId = this.getAttribute('data-product-id');
            updateCartQuantity(productId, -1);
        });
    });
    
    // 增加数量按钮
    document.querySelectorAll('.cart-increase').forEach(button => {
        button.addEventListener('click', function() {
            const productId = this.getAttribute('data-product-id');
            updateCartQuantity(productId, 1);
        });
    });
    
    // 数量输入框
    document.querySelectorAll('.cart-quantity').forEach(input => {
        input.addEventListener('change', function() {
            const productId = this.getAttribute('data-product-id');
            const newQuantity = parseInt(this.value);
            
            if (isNaN(newQuantity) || newQuantity < 1) {
                this.value = 1;
                updateCartQuantity(productId, 1);
            } else {
                updateCartQuantity(productId, newQuantity, true);
            }
        });
    });
    
    // 删除商品按钮
    document.querySelectorAll('.cart-remove').forEach(button => {
        button.addEventListener('click', function() {
            const productId = this.getAttribute('data-product-id');
            removeFromCart(productId);
        });
    });
    
    // 清空购物车按钮
    const clearCartButton = document.getElementById('clear-cart');
    if (clearCartButton) {
        clearCartButton.addEventListener('click', clearCart);
    }
}

// 更新购物车商品数量
function updateCartQuantity(productId, change, setExact = false) {
    const cart = JSON.parse(localStorage.getItem('cart')) || [];
    const itemIndex = cart.findIndex(item => item.id === productId);
    
    if (itemIndex !== -1) {
        if (setExact) {
            cart[itemIndex].quantity = change;
        } else {
            cart[itemIndex].quantity += change;
        }
        
        // 如果数量小于等于0，移除商品
        if (cart[itemIndex].quantity <= 0) {
            cart.splice(itemIndex, 1);
        }
        
        // 保存购物车
        localStorage.setItem('cart', JSON.stringify(cart));
        
        // 重新渲染购物车
        renderCartItems();
        initCartItemEvents();
        
        // 更新购物车数量
        updateCartCount();
    }
}

// 从购物车移除商品
function removeFromCart(productId) {
    const cart = JSON.parse(localStorage.getItem('cart')) || [];
    const itemIndex = cart.findIndex(item => item.id === productId);
    
    if (itemIndex !== -1) {
        const itemName = cart[itemIndex].name;
        cart.splice(itemIndex, 1);
        
        // 保存购物车
        localStorage.setItem('cart', JSON.stringify(cart));
        
        // 显示通知
        showNotification(`${itemName} 已从购物车移除`, 'info');
        
        // 重新渲染购物车
        renderCartItems();
        initCartItemEvents();
        
        // 更新购物车数量
        updateCartCount();
    }
}

// 清空购物车
function clearCart() {
    localStorage.setItem('cart', JSON.stringify([]));
    
    // 显示通知
    showNotification('购物车已清空', 'info');
    
    // 重新渲染购物车
    renderCartItems();
    initCartItemEvents();
    
    // 更新购物车数量
    updateCartCount();
}

// 渲染结账页面商品
function renderCheckoutItems() {
    const cart = JSON.parse(localStorage.getItem('cart')) || [];
    const checkoutItemsContainer = document.getElementById('checkout-items');
    
    if (!checkoutItemsContainer) return;
    
    // 清空容器
    checkoutItemsContainer.innerHTML = '';
    
    if (cart.length === 0) {
        // 购物车为空，重定向到购物车页面
        window.location.href = 'cart.html';
        return;
    }
    
    // 显示购物车商品
    cart.forEach(item => {
        const itemTotal = item.price * item.quantity;
        
        const checkoutItem = document.createElement('div');
        checkoutItem.className = 'flex items-center py-3 border-b border-light-2';
        checkoutItem.innerHTML = `
            <div class="w-16 h-16 rounded-lg overflow-hidden">
                <img src="${item.image}" alt="${item.name}" class="w-full h-full object-cover">
            </div>
            <div class="ml-3 flex-1">
                <h4 class="font-medium">${item.name}</h4>
                <p class="text-sm text-dark-2">¥${item.price.toFixed(2)} × ${item.quantity}</p>
            </div>
            <div class="text-right font-medium">¥${itemTotal.toFixed(2)}</div>
        `;
        
        checkoutItemsContainer.appendChild(checkoutItem);
    });
}

// 计算结账页面总计
function calculateCheckoutTotals() {
    const cart = JSON.parse(localStorage.getItem('cart')) || [];
    
    // 计算小计
    const subtotal = cart.reduce((total, item) => total + (item.price * item.quantity), 0);
    
    // 计算运费 (假设满199免运费)
    const shipping = subtotal >= 199 ? 0 : 15;
    
    // 计算总计
    const total = subtotal + shipping;
    
    // 更新DOM
    document.getElementById('checkout-subtotal').textContent = `¥${subtotal.toFixed(2)}`;
    document.getElementById('checkout-shipping').textContent = `¥${shipping.toFixed(2)}`;
    document.getElementById('checkout-total').textContent = `¥${total.toFixed(2)}`;
}    